package constant.milk.cashbook.category;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import constant.milk.cashbook.MainActivity;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.asset.CountActivity;
import constant.milk.cashbook.asset.NameActivity;
import constant.milk.cashbook.bean.CategoryMainData;
import constant.milk.cashbook.bean.CategorySubData;
import constant.milk.cashbook.bean.InOutData;
import constant.milk.cashbook.database.DBSelectQuery;
import constant.milk.cashbook.database.DbDeleteQuery;
import constant.milk.cashbook.database.DbInsertQuery;
import constant.milk.cashbook.database.DbUpdateQuery;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.MilkTextView;
import constant.milk.cashbook.util.MilkUtil;

public class CategoryUpdateActivity extends SuperActivity
{
	public static final String MAIN_CATEGORY_ID = "MAIN_CATEGORY_ID";
	
	private static final int NAME_REQUEST_CODE = 0;
	private static final int COUNT_REQUEST_CODE = 1;
	private static final int SUB_CATEGORY_INSERT_REQUEST_CODE = 2;
	private static final int SUB_CATEGORY_UPDATE_REQUEST_CODE = 3;
	
	private View nameView;
	private View countView;;
	private View subCategoryView;
	
	private TextView nameTextView;
	private TextView countTextView;
	
	private ListView listView;
	
	private Button deleteButton;
	private Button updateButton;
	
	private ArrayList<CategorySubData> list;
	
	private SubCategoryListAdapter adapter;
	
	private CategoryMainData mainData;
	
	private DBSelectQuery select;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.category_update_activity);
		
		setTitle("메인수정");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		nameView = findViewById(R.id.categoryUpdateNameView);
		countView = findViewById(R.id.categoryUpdateCountView);
		subCategoryView = findViewById(R.id.categoryUpdateSubView);
		
		nameTextView = (TextView) findViewById(R.id.categoryUpdateNameTextView);
		countTextView = (TextView) findViewById(R.id.categoryUpdateCountTextView);
		
		listView = (ListView) findViewById(R.id.listView);
		
		deleteButton = (Button) findViewById(R.id.deleteButton);
		updateButton = (Button) findViewById(R.id.updateButton);
	}

	@Override
	protected void setOnClick()
	{
		nameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, NameActivity.class);
				intent.putExtra(NameActivity.NAME_DATA, nameTextView.getText().toString());
				startActivityForResult(intent, NAME_REQUEST_CODE);
			}
		});
		
		countView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, CountActivity.class);
				intent.putExtra(CountActivity.COUNT_DATA, countTextView.getText().toString());
				startActivityForResult(intent, COUNT_REQUEST_CODE);
			}
		});
		
		subCategoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, NameActivity.class);
				intent.putExtra(NameActivity.NAME_DATA, "");
				startActivityForResult(intent, SUB_CATEGORY_INSERT_REQUEST_CODE);
			}
		});
		
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (setDeleteData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", 
							"삭제에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (setCheckData())
				{
					return;
				}
				
				if (setUpdateData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 저장에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		select = new DBSelectQuery(superContext, superDb);
		
		Intent intent = getIntent();
		
		String id = intent.getStringExtra(MAIN_CATEGORY_ID);
		
		mainData = select.getCategoryMainId(id);
		
		list = select.getCategorySubList(mainData.getId());
		
		nameTextView.setText(mainData.getName());
		countTextView.setText(mainData.getCount());
		
		listView.setOnItemClickListener(onItemClickListener);
		
		adapter = new SubCategoryListAdapter(
				superContext, R.layout.normal_list_item, list);
		listView.setAdapter(adapter);
	}
	
	/**
	 * 테이터가 제대로 있는지 확인한다.
	 */
	private boolean setCheckData()
	{
		String name = nameTextView.getText().toString();
		
		if (name.equals("") || name.length() < 1)
		{
			MilkUtil.showDialog(superContext, "확인", "이름을 입력해주세요.");
			return true;
		}
		
		if (list.size() < 1)
		{
			MilkUtil.showDialog(superContext, "확인", "서브 카테고리를 추가해주세요.");
			return true;
		}
		
		return false;
	}
	
	private boolean setDeleteData()
	{
		DbDeleteQuery query = null;
		try
		{
			query = new DbDeleteQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			query.setCategoryMainDelete(mainData.getId());
			
			query.setCategorySubDeleteLinkId(mainData.getId());
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setUpdateData()
	{
		DbUpdateQuery query = null;
		
		try
		{
			query = new DbUpdateQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("name", nameTextView.getText().toString());
			map.put("count", countTextView.getText().toString());
			
			query.setCategoryMainUpdate(map, mainData.getId());
			
			map.clear();
			map.put("maincategory", nameTextView.getText().toString());
			
			ArrayList<InOutData> list = select.getInOutMainCategoryList(mainData.getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				query.setInOutUpdate(map, list.get(i).getId());
			}
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
		
		if (requestCode == NAME_REQUEST_CODE)
		{
			String str = data.getStringExtra(NameActivity.NAME_DATA);
			
			DBSelectQuery query = new DBSelectQuery(superContext, superDb);
			
			int count = query.getCategoryMainCount(str);
			
			if (count > 0)
			{
				MilkUtil.showToast(superContext, "같은 이름의 메인 카테고리가 있습니다.");
				return;
			}
			
			nameTextView.setText(str);
		}
		else if (requestCode == COUNT_REQUEST_CODE)
		{
			String str = data.getStringExtra(CountActivity.COUNT_DATA);
			
			countTextView.setText(str);
		}
		else if (requestCode == SUB_CATEGORY_INSERT_REQUEST_CODE)
		{
			String str = data.getStringExtra(NameActivity.NAME_DATA);
			
			DbInsertQuery insertQuery =	null;
			
			try
			{
				insertQuery = new DbInsertQuery(superContext, superDb);
				
				insertQuery.setBeginTansaction();
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("name", str);
				map.put("count", "0");
				map.put("linkid", mainData.getId());
				
				insertQuery.setCategorySub(map);
				
				insertQuery.setSuccessful();
			} catch (Exception e)
			{
				e.printStackTrace();
				MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
			} finally {
				try
				{
					insertQuery.setEndTansaction();
				} catch (Exception e)
				{
					e.printStackTrace();
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
			
			DBSelectQuery query = new DBSelectQuery(superContext, superDb);
			list = query.getCategorySubList(mainData.getId());
			
			listView.setOnItemClickListener(onItemClickListener);
			
			adapter = new SubCategoryListAdapter(
					superContext, R.layout.normal_list_item, list);
			listView.setAdapter(adapter);
			adapter.notifyDataSetChanged();
		}
		else if (requestCode == SUB_CATEGORY_UPDATE_REQUEST_CODE)
		{
			DBSelectQuery query = new DBSelectQuery(superContext, superDb);
			list = query.getCategorySubList(mainData.getId());
			
			listView.setOnItemClickListener(onItemClickListener);
			
			adapter = new SubCategoryListAdapter(
					superContext, R.layout.normal_list_item, list);
			listView.setAdapter(adapter);
			adapter.notifyDataSetChanged();
		}
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			CategorySubData data = (CategorySubData) arg0.getItemAtPosition(position);
			
			Intent intent = new Intent(superContext, CategorySubUpdateActivity.class);
			intent.putExtra(CategorySubUpdateActivity.SUB_CATEGORY_ID, data.getId());
			intent.putExtra(CategorySubUpdateActivity.MAIN_CATEGORY_ID, mainData.getId());
			startActivityForResult(intent, SUB_CATEGORY_UPDATE_REQUEST_CODE);
		}
	};
	
	/**
	 * 리스트 아답터
	 */
	private class SubCategoryListAdapter extends ArrayAdapter<CategorySubData> 
	{
		public SubCategoryListAdapter(Context context, int textViewResourceId, ArrayList<CategorySubData> list) 
		{
			super(context, textViewResourceId, list);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View v = convertView;
			
			if (v == null) 
			{
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.normal_list_item, null);
			}
			
			CategorySubData data = getItem(position);
			
			MilkTextView nameTextView = (MilkTextView) v.findViewById(R.id.normalItemNameTextView);
			
			nameTextView.setTextSize(TEXT_SIZE);
			nameTextView.setText(data.getName());
			
			return v;
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_CATEGORY_INFO);
		startActivity(intent);
	}

}
